<%-- 
    Document   : rater
    Created on : May 8, 2013, 3:16:35 AM
    Author     : Lord Makuta
--%>

<%@page import="java.util.ArrayList"%>
<%@page import="db.UserDAO"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page import="db.DB"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%
    if (session.getAttribute("user")==null)
    {
        response.sendRedirect("index.jsp");
    }

    String m=request.getParameter("movie");
    String a=request.getParameter("actor");
    int rate=Integer.parseInt(request.getParameter("score"));
    int uId=((UserDAO)session.getAttribute("user")).getId();
    
    DB data=new DB();
    Connection conn=null;
    Statement stm=null;
    ResultSet res=null;
    
    ArrayList scores=new ArrayList();
    
    try
    {
        conn=data.getConnection();
        stm=conn.createStatement();
        if (m!=null && !m.equals(""))
        {
            int mId=Integer.parseInt(m);
            String mQ="INSERT INTO MovieRatings (CustomerId, MovieId, Rate) VALUES ("+uId +", "+mId+", "+rate+")";
            String upM="UPDATE Movie SET Rating=(SELECT AVG(Rate) FROM MovieRatings WHERE MovieId="+mId+") WHERE Id="+mId;
    
            stm.executeUpdate(mQ);
            stm.executeUpdate(upM);
            conn.close();
            conn=null;
            response.sendRedirect("movie.jsp?id="+mId);
        }
        else if (a!=null && !a.equals(""))
        {
            int aId=Integer.parseInt(a);
            String aQ="INSERT INTO ActorRatings (CustomerId, ActorId, Rate) VALUES ("+uId +", "+aId+", "+rate+")";
            String upA="UPDATE Actor SET Rating=(SELECT AVG(Rate) FROM ActorRatings WHERE ActorId="+aId+") WHERE Id="+aId;
            
            stm.executeUpdate(aQ);
            stm.executeUpdate(upA);
            conn.close();
            conn=null;
            response.sendRedirect("actor.jsp?id="+aId);
        }
        else
        {
            conn.close();
            conn=null;
            response.sendRedirect("index.jsp");
        }
    }
    catch (Exception e)
    {
        
    }
    
%>
